package bb.lanxing.util.pop;

import static android.webkit.WebSettings.LOAD_NO_CACHE;

import com.tbruyelle.rxpermissions3.RxPermissions;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentActivity;

import bb.lanxing.App;
import bb.lanxing.BuildConfig;
import bb.lanxing.MainActivity;
import bb.lanxing.R;
import bb.lanxing.activity.login.PhoneBindActivity;
import bb.lanxing.common.config.Constants;
import bb.lanxing.manager.SharedManager;
import bb.lanxing.model.database.User;
import bb.lanxing.util.RxPermissionUtil;
import bb.lanxing.view.BiciAlertDialogBuilder;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;

public class Inspector {
    private static Inspector INSTANTS = null;
    private static MainActivity mainActivity;
    static Task taskCheckAppPermission;
    static Task taskCheckUserAgreement;
    static Task taskCheckUserPhoneBind;
    static Task taskCheckVersionDetailShow;
    static Task taskRequestAppPermission;
    private static TaskManager taskManagerRuntime = new TaskManager();
    static int priorityCheckUserPhoneBind = 2;
    static int priorityCheckUserAgreement = 3;
    static int priorityCheckVersionDetailShow = 5;
    static int priorityCheckAppPermission = 6;
    static int priorityRequestAppPermission = 7;
    public static String KEY_IS_REQUEST = "KEY_IS_REQUEST";

    public static Inspector getInstance() {
        if (INSTANTS == null) {
            synchronized (Inspector.class) {
                if (INSTANTS == null) {
                    INSTANTS = new Inspector();
                }
            }
        }
        return INSTANTS;
    }

    private Inspector() {
    }

    public static void inspectRuntime(MainActivity fragmentActivity) {
        mainActivity = fragmentActivity;
        taskManagerRuntime.interruptAllTasks();
        TaskManager taskManager = new TaskManager();
        taskManagerRuntime = taskManager;
        if (taskManager.isEmpty()) {
            taskManagerRuntime
//                    .pushToQueue(getTaskDomainCheck(fragmentActivity, taskManagerRuntime))
                    .pushToQueue(getTaskCheckUserPhoneBind(fragmentActivity, taskManagerRuntime))
                    //.pushToQueue(getTaskCheckUserAgreement(fragmentActivity, taskManagerRuntime))
                    //.pushToQueue(getTaskCheckVersionDetailShow(fragmentActivity, taskManagerRuntime))
                    .pushToQueue(getTaskCheckAppPermission(fragmentActivity, taskManagerRuntime));
//                    pushToQueue(getTaskRequestUserPopWindow(fragmentActivity, taskManagerRuntime));
//                    pushToQueue(getTaskCheckUserPopWindowTypeAd(fragmentActivity, taskManagerRuntime));
            taskManager.runTask();
        }
    }

    public static void interruptRuntime() {
        taskManagerRuntime.interruptAllTasks();
    }

    public static Task getTaskCheckAppPermission(final FragmentActivity fragmentActivity, final TaskManager taskManager) {
        Task taskWork = new Task().setTaskId(priorityCheckAppPermission).setPriority(priorityCheckAppPermission).setTaskWork(new Task.TaskWork() {
            @Override
            public void onWorkInterrupt(Task task) {
            }

            @Override
            public void onWorkRun(Task task) {
                if (!RxPermissionUtil.getInstance().checkPermission(fragmentActivity, RxPermissionUtil.getInspectorPermissions())) {
                    boolean result = SharedManager.getInstance().getBoolean(Inspector.KEY_IS_REQUEST, false);
                    if (!result && App.getContext().isUserSignin()) {
                        SharedManager.getInstance().setValue(Inspector.KEY_IS_REQUEST, true);
                        task.addPopDialog(Inspector.getCheckPermissionDialog(fragmentActivity, taskManager));
                    }
                    taskManager.onTaskGoSuccess(task);
                    return;
                }
                taskManager.onTaskInterrupt(task);
                App.getContext().initManagersWithPermissions();
            }
        });
        taskCheckAppPermission = taskWork;
        return taskWork;
    }

    public static Task getTaskRequestAppPermission(final FragmentActivity fragmentActivity, final TaskManager taskManager) {
        Task taskWork = new Task().setTaskId(31).setPriority(priorityRequestAppPermission).setTaskWork(new Task.TaskWork() {

            @Override
            public void onWorkInterrupt(Task task) {
            }

            @Override
            public void onWorkRun(final Task task) {
                new RxPermissions(fragmentActivity).request(RxPermissionUtil.getInspectorPermissions()).subscribe(new Observer<Boolean>() {

                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(Boolean bool) {
                        if (bool) {
                            App.getContext().initManagersWithPermissions();
                        } else {
                            taskManager.dismissCurrent();
                        }
                        taskManager.onTaskGoSuccess(task);
                    }

                    @Override
                    public void onError(Throwable th) {
                        th.printStackTrace();
                    }

                    @Override
                    public void onComplete() {

                    }
                });
            }
        });
        taskRequestAppPermission = taskWork;
        return taskWork;
    }

    public static Task getTaskCheckUserPhoneBind(Activity activity, final TaskManager taskManager) {
        Task taskWork = new Task().setTaskId(priorityCheckUserPhoneBind).setPriority(priorityCheckUserPhoneBind).addPopDialog(getBindPhoneDialog(activity, taskManager)).setTaskWork(new Task.TaskWork() {
            @Override
            public void onWorkInterrupt(Task task) {
            }

            @Override
            public void onWorkRun(Task task) {
                User signinUser = App.getContext().getSigninUser();
                if (signinUser != null && signinUser.getPhone() != null && signinUser.getPhone().isEmpty()) {
                    boolean ret = SharedManager.getInstance().isUseAgreementAgree(signinUser.getUid());
                    if (ret) {
                        taskManager.onTaskGoSuccess(task);
                    } else {
                        taskManager.onTaskInterrupt(task);
                    }
                } else {
                    taskManager.onTaskInterrupt(task);
                }
            }
        });
        taskCheckUserPhoneBind = taskWork;
        return taskWork;
    }

    public static Task getTaskCheckUserAgreement(Activity activity, final TaskManager taskManager) {
        Task taskWork = new Task().setTaskId(priorityCheckUserAgreement).setPriority(priorityCheckUserAgreement).addPopDialog(getUserAgreementDialog(activity, taskManager)).setTaskWork(new Task.TaskWork() {
            @Override
            public void onWorkInterrupt(Task task) {
            }

            @Override
            public void onWorkRun(Task task) {
                if (App.getContext().getSigninUser() != null) {
                    if (!SharedManager.getInstance().isUseAgreementAgree(App.getContext().getSigninUser().getUid())) {
                        taskManager.onTaskGoSuccess(task);
                        return;
                    }
                    taskManager.onTaskInterrupt(task);
                    if (!App.getContext().isSdkInit) {
                        App.getContext().initAfterUserAgree();
                    }
                    if (Inspector.mainActivity != null) {
                        Inspector.mainActivity.refreshFragmentData();
                    }
                } else if (!SharedManager.getInstance().isUseAgreementAgree(1)) {
                    taskManager.onTaskGoSuccess(task);
                } else {
                    taskManager.onTaskInterrupt(task);
                    if (!App.getContext().isSdkInit) {
                        App.getContext().initAfterUserAgree();
                    }
                    if (Inspector.mainActivity != null) {
                        Inspector.mainActivity.refreshFragmentData();
                    }
                }
            }
        });
        taskCheckUserAgreement = taskWork;
        return taskWork;
    }

    public static Task getTaskCheckVersionDetailShow(Activity activity, final TaskManager taskManager) {
        Task taskWork = new Task().setTaskId(priorityCheckVersionDetailShow).setPriority(priorityCheckVersionDetailShow).addPopDialog(getVersionDetailDialog(activity, taskManager)).setTaskWork(new Task.TaskWork() {
            @Override
            public void onWorkInterrupt(Task task) {
            }

            @Override
            public void onWorkRun(Task task) {
                String versionName = App.getContext().getVersionName();
                String versionName2 = SharedManager.getInstance().getVersionName();
                SharedManager.getInstance().setVersionName(versionName);
                if (versionName2.isEmpty() || Inspector.needShowVersionDes(versionName2, versionName)) {
                    taskManager.onTaskGoSuccess(task);
                } else {
                    taskManager.onTaskInterrupt(task);
                }
            }
        });
        taskCheckVersionDetailShow = taskWork;
        return taskWork;
    }

    public static PopDialog getCheckPermissionDialog(final FragmentActivity fragmentActivity, final TaskManager taskManager) {
        return new PopDialog.Builder().setUid(priorityCheckAppPermission).setContext(fragmentActivity).setPriority(priorityCheckAppPermission).setDialog(new BiciAlertDialogBuilder(fragmentActivity).setTitle(R.string.permission_prompt).setCancelable(false).setMessage(fragmentActivity.getString(R.string.permission_content)).setPositiveButton(R.string.dialog_btn_goto_setting, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                taskManager.dismissCurrent();
                TaskManager taskManager2 = taskManager;
                taskManager2.pushToQueue(Inspector.getTaskRequestAppPermission(fragmentActivity, taskManager2));
                taskManager.runTask();
            }
        }).setNegativeButton(R.string.skip, (dialogInterface, i) -> {
            taskManager.dismissCurrent();
            App.getContext().initManagersWithPermissions();
        }).create()).build();
    }

    private static PopDialog getBindPhoneDialog(final Activity activity, final TaskManager taskManager) {
        return new PopDialog.Builder().setUid(priorityCheckUserPhoneBind).setContext(activity).setPriority(priorityCheckUserPhoneBind).setDialog(new BiciAlertDialogBuilder(activity).setTitle(activity.getString(R.string.st_ti_bind_phone)).setMessage(activity.getResources().getString(R.string.st_des_bind_phone)).setCancelable(true).setPositiveButton(R.string.st_action_bind_phone, (dialogInterface, i) -> {
            activity.startActivity(new Intent(activity, PhoneBindActivity.class).putExtra("user_id", App.getContext().getSigninUser().getUid()).putExtra("canBack", false));
            taskManager.dismissCurrent();
        }).create()).build();
    }

    public static PopDialog getUserAgreementDialog(Activity activity, final TaskManager taskManager) {
        View inflate = LayoutInflater.from(activity).inflate(R.layout.dialog_user_agreement, null);
        WebView webView = inflate.findViewById(R.id.webView);
        webView.setWebViewClient(new WebViewClient());
        webView.setWebChromeClient(new WebChromeClient());
        webView.getSettings().setJavaScriptEnabled(true);//todo sst
        webView.getSettings().setCacheMode(LOAD_NO_CACHE);
//        webView.loadUrl("file:////android_asset/document/485/index.html");
        webView.loadUrl(Constants.URL_PRIVACY_AGREEMENT);
        View agree = inflate.findViewById(R.id.agree);
        View disagree = inflate.findViewById(R.id.disagree);
        final ProgressBar progressBar = inflate.findViewById(R.id.progressBar);
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView webView2, int i) {
                if (i == 100) {
                    progressBar.setVisibility(View.GONE);
                    return;
                }
                progressBar.setVisibility(View.VISIBLE);
                progressBar.setProgress(i);
            }
        });
        PopDialog dialog = new PopDialog.Builder().setUid(103).setContext(activity).setPriority(priorityCheckUserAgreement).setDialog(new BiciAlertDialogBuilder(activity).setView(inflate).setCancelable(false).create()).build();
        agree.setOnClickListener(view -> {
            if (taskManager == null) {
                dialog.getDialog().dismiss();
            } else {
                taskManager.dismissCurrent();
            }
            if (!App.getContext().isSdkInit) {
                App.getContext().initAfterUserAgree();
            }
            if (App.getContext().getSigninUser() != null) {
                SharedManager.getInstance().setUserAgreement(App.getContext().getSigninUser().getUid(), true);
            } else {
                SharedManager.getInstance().setUserAgreement(1, true);
            }
            if (Inspector.mainActivity != null) {
                Inspector.mainActivity.refreshFragmentData();
            }
        });
        disagree.setOnClickListener(view -> {
            if (taskManager == null) {
                dialog.getDialog().dismiss();
            } else {
                taskManager.dismissCurrent();
            }
        });
        return dialog;
    }

    private static PopDialog getVersionDetailDialog(Activity activity, final TaskManager taskManager) {
        View inflate = LayoutInflater.from(activity).inflate(R.layout.new_version_dialog_view, null);
        WebView webView = inflate.findViewById(R.id.webView);
        webView.setWebViewClient(new WebViewClient());
        webView.setWebChromeClient(new WebChromeClient());
        webView.getSettings().setJavaScriptEnabled(true);//todo sst, need check
        webView.getSettings().setCacheMode(LOAD_NO_CACHE);
        webView.loadUrl(Constants.NEW_VERSION);
        ((TextView) inflate.findViewById(R.id.tvTitle)).setText(activity.getString(R.string.app_upgrade_doc_title, BuildConfig.VERSION_NAME));
        inflate.findViewById(R.id.tvKnown).setOnClickListener(view -> taskManager.dismissCurrent());
        return new PopDialog.Builder().setUid(104).setContext(activity).setPriority(priorityCheckVersionDetailShow).setDialog(new BiciAlertDialogBuilder(activity).setCancelable(true).setOnCancelListener(dialogInterface -> taskManager.dismissCurrent()).setView(inflate).create()).build();
    }

    public static boolean needShowVersionDes(String str, String str2) {
        String[] split = str.split("\\.");
        String[] split2 = str2.split("\\.");
        if (split.length == 3 && split2.length == 3) {
            for (int i = 0; i < split.length - 1; i++) {
                try {
                    if (Integer.parseInt(split[i]) < Integer.parseInt(split2[i])) {
                        return true;
                    }
                } catch (Exception unused) {
                }
            }
        }
        return false;
    }
}
